<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/2/26
 * Time: 11:35
 */

namespace app\api\service;

use app\common\Model\Freight;
use app\common\Model\Region;
use app\common\Server\Redis;
use app\common\Service;
use think\Db;

class RegionService extends Service
{
    /**
     * 保存更新地址信息词典
     * @return bool
     * todo 需整理逻辑
     */
    public function regionList()
    {
        $str = 'CACHE:REGION:LIST';
        $city_list = Db::table('sh_freight')->field('city_region_id,province_region_id')
            ->where(['is_del' => 0])
            ->select();

        $city_ids = [];
        foreach ($city_list as $item){
            $city_ids[] = $item['city_region_id'];
            $city_ids[] = $item['province_region_id'];
        }

        //查询省份信息
        $list = Db::table('sh_region')
            ->where('region_id in ('.implode(',',$city_ids).')')->select();

        $area = Db::table('sh_region')
            ->where('parent_id in ('.implode(',',$city_ids).')')
            ->where(['level' => 3])
            ->select();

        $area_list = [];
        foreach ($area as $item){
            $area_list[$item['parent_id']][] = $item;
        }

        $province = [];
        foreach ($list as $item){
            if($item['level'] == 1){
                $province[] = $item;
            }
        }
        foreach ($list as $item){
            foreach ($province as &$pitem){
                if(isset($pitem['region_id']) && $item['parent_id'] == $pitem['region_id']){
                    $pitem['child'][] = $item;
                }
            }
        }

        foreach ($province as &$pitem){
            if(isset($pitem['child']) && is_array($pitem['child'])){
                foreach ($pitem['child'] as &$citem){
                    $citem['child'] = $area_list[$citem['region_id']];
                }
            }
        }

        $redis = new Redis();

        $rtn = $redis->set($str,json_encode($province));
        if($rtn){
            return true;
        }
        return false;
    }
}